/*
 * Copyright 2013 Rodrigo Villablanca <villa061004@gmail.com>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cl.rvillablanca.jpatch;

import cl.rvillablanca.jpatch.gui.View;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;

/**
 *
 * @author Rodrigo Villablanca <villa061004@gmail.com>
 */
public class JPatch {

    private static final Logger LOGGER = Logger.getLogger(JPatch.class.getName());
    private static final String JPATCH_HOME = System.getProperty("user.home")
            + System.getProperty("file.separator")
            + ".jpatch";
    private static final String JPATCH_LOG_CONFIG_URL = JPATCH_HOME
            + System.getProperty("file.separator")
            + "log.properties";

    public static void loadLogConfiguration() {
        LOGGER.info("Checking JPatch home ...");
        Path homePath = Paths.get(JPATCH_HOME);
        if (Files.notExists(homePath)) {
            try {
                LOGGER.info("Creating JPatch home ...");
                Files.createDirectory(homePath);
                if (Files.exists(homePath)) {
                    LOGGER.info("JPatch home created");
                    LOGGER.info("Creating default log file ...");
                    Path logPat = Paths.get(JPATCH_LOG_CONFIG_URL);
                    Files.createFile(logPat);
                    try (InputStream is = JPatch.class.getResourceAsStream("/log.properties");
                            OutputStream os = new FileOutputStream(JPATCH_LOG_CONFIG_URL)) {
                        byte[] bytes = new byte[4096];
                        int read = is.read(bytes);
                        while (read != -1) {
                            os.write(bytes);
                            read = is.read(bytes);
                        }
                    }
                    LOGGER.info("Log file created");
                    loadLogFileConfiguration();
                } else {
                    LOGGER.info("Cannot create log file");
                }
            } catch (IOException ex) {
                LOGGER.log(Level.INFO, "Cannot create JPatch home, {0}", ex.getMessage());
            }
        } else if (!Files.exists(homePath)) {
            LOGGER.info("Can not get information about JPatch home");
        } else {
            LOGGER.info("JPatch home exist");
            loadLogFileConfiguration();
        }
    }

    private static void loadLogFileConfiguration() {
        LOGGER.info("Loading log configuration ...");
        try (InputStream is = new FileInputStream(JPATCH_LOG_CONFIG_URL)) {
            LogManager.getLogManager().readConfiguration(is);
            LOGGER.info("Log configuration loaded");
        } catch (FileNotFoundException ex) {
            LOGGER.log(Level.INFO, "Can't load log file {0}", JPATCH_LOG_CONFIG_URL);
            loadDefaultLogConfiguration();
        } catch (SecurityException | IOException ex) {
            LOGGER.log(Level.INFO, "Can't load log file: {0}", ex.getMessage());
            loadDefaultLogConfiguration();
        }
    }

    private static void loadDefaultLogConfiguration() {
        try {
            LOGGER.info("Loading default configuration");
            InputStream is = JPatch.class.getResourceAsStream("/log.properties");
            LogManager.getLogManager().readConfiguration(is);
            LOGGER.info("Default log configuration loaded");
        } catch (IOException | SecurityException ex) {
            LOGGER.info("Can't load default configuration, nothing to do");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                loadLogConfiguration();
                new View().setVisible(true);
            }
        });
    }
}
